package com.eims.main.livescores.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.AuthorStringRequest;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.StringRequest;
import com.contans.view.BifenGetFootBallTeamVo;
import com.contans.view.getINdexFootballdayVo;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.utils.NetWork;
import com.eims.sls_app.utils.UnicodeUtil;
import com.eims.sls_app.view.MyToast;
import com.eims.sls_app.view.PullToRefreshView;
import com.eims.sls_app.view.PullToRefreshView.OnHeaderRefreshListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.TextView;
import bls.juejin.cn.R;
import progressBar.ProgressDialogBar;

public class MainZqBifenFragment extends Fragment implements OnHeaderRefreshListener {
	private Activity activity;

	private String dataTime;
	private PullToRefreshView mPullToRefreshView;

	private List<getINdexFootballdayVo> maplist;
	private ArrayList<BifenGetFootBallTeamVo> arrayList;
	// View
	private ExpandableListView expandableListView;
	private MyHandler myHandler;

	private MyExpandableListView adapter;
	private int reshId = 0;
	
	private int getRealId=0;
	private  boolean isFresh;


	public MainZqBifenFragment() {
		super();
	}

	public static MainZqBifenFragment newInstance(boolean isFresh) {

		Bundle args = new Bundle();

		MainZqBifenFragment fragment = new MainZqBifenFragment();
		args.putBoolean("isFresh",isFresh);
		fragment.setArguments(args);
		return fragment;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_zq_bifen, container, false);
		activity = getActivity();
		Bundle bundle=getArguments();
		if (bundle!=null){
			this.isFresh=bundle.getBoolean("isFresh");
		}
		myHandler = new MyHandler();
		adapter = new MyExpandableListView(activity, maplist);
		init(view);

		return view;
	}

	private void init(View view) {
		// TODO Auto-generated method stub
		expandableListView = (ExpandableListView) view.findViewById(R.id.expandableListView);
		mPullToRefreshView = (PullToRefreshView) view.findViewById(R.id.mPullToRefreshView);

		mPullToRefreshView.setOnHeaderRefreshListener(this);
		
		
		ProgressDialogBar.show(activity, dataTime, false);
//		expandableListView.setSelectedChild(groupPosition, childPosition, shouldExpandGroup)

		expandableListView.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
				// TODO Auto-generated method stub
				return true;
			}
		});
		
		expandableListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
				reshId=firstVisibleItem;
				
			}
		});

	}

	public void getSaomaXplay() {
		
		
		getRealId=reshId;
		Log.e("------", getRealId+"");
		MySingleton mySingleton = MySingleton.getInstance(activity);
		
		Log.i("RealTime", "request--------success------" +"http://nlive.159cai.com/live/home/matchlist?type=jc&issue=" + LotteryUtils.getStringDateShort());


		AuthorStringRequest jsonObjectRequest = new AuthorStringRequest(Request.Method.GET,
				"http://nlive.159cai.com/live/home/matchlist?type=jc&issue=" + LotteryUtils.getStringDateShort(),
				// "http://nlive.159cai.com/live/home/matchlist?type=jc&issue=2018-01-06",
				new Response.Listener<String>() {
					@Override
					public void onResponse(String tn) {

						String getToJson = UnicodeUtil.decodeUnicode(tn);

						Log.i("RealTime", "request--------success------" + getToJson);

						maplist = new ArrayList<getINdexFootballdayVo>();

						try {
							JSONObject item = new JSONObject(getToJson);
							if ("success".equals(item.optString("msg"))) {
								String data = item.optString("data");

								if (!data.equals("")) {
									JSONObject array2 = new JSONObject(data);

									String matchlist_block = array2.optString("matchlist_block");

									if (!"".equals(matchlist_block)) {
										JSONObject mapJSON = array2.getJSONObject("matchlist_block");

										// 动态获取key值
										Iterator<String> iterator = mapJSON.keys();
										while (iterator.hasNext()) {
											String key = iterator.next();
											String keyStr = mapJSON.getString(key);
											getINdexFootballdayVo footballdayVo = new getINdexFootballdayVo();
											if (keyStr != null && !"[]".equals(keyStr)) {
												arrayList = new ArrayList<BifenGetFootBallTeamVo>();

												JSONArray team_key = new JSONArray(keyStr);
												BifenGetFootBallTeamVo ballTeamVo;
												for (int i = 0; i < team_key.length(); i++) {
													JSONObject keyJSON = team_key.getJSONObject(i);
													ballTeamVo = new BifenGetFootBallTeamVo();
													ballTeamVo.ab = keyJSON.getString("ab");

													ballTeamVo.htid = keyJSON.getString("htid");
													ballTeamVo.color = keyJSON.getString("color");
													ballTeamVo.alogo = keyJSON.getString("alogo");
													ballTeamVo.hrank = keyJSON.getString("hrank");
													ballTeamVo.hteam = keyJSON.getString("hteam");
													ballTeamVo.hred = keyJSON.getString("hred");

													ballTeamVo.weather = keyJSON.getString("weather");
													ballTeamVo.mtime = keyJSON.getString("mtime");
													ballTeamVo.lid = keyJSON.getString("lid");
													ballTeamVo.hlogo = keyJSON.getString("hlogo");
													ballTeamVo.ared = keyJSON.getString("ared");
													ballTeamVo.letball = keyJSON.getString("letball");

													ballTeamVo.xid = keyJSON.getString("xid");
													ballTeamVo.realtime = keyJSON.getString("realtime");
													ballTeamVo.exflag = keyJSON.getString("exflag");
													ballTeamVo.mid = keyJSON.getString("mid");
													ballTeamVo.tp = keyJSON.getString("tp");

													ballTeamVo.lname = keyJSON.getString("lname");
													ballTeamVo.state = keyJSON.getString("state");
													ballTeamVo.ascore = keyJSON.getString("ascore");
													ballTeamVo.bets = keyJSON.getString("bets");
													ballTeamVo.be = keyJSON.getString("be");

													ballTeamVo.openflag = keyJSON.getString("openflag");
													ballTeamVo.half = keyJSON.getString("half");
													ballTeamVo.atid = keyJSON.getString("atid");
													ballTeamVo.weatherinfo = keyJSON.getString("weatherinfo");
													ballTeamVo.remark = keyJSON.getString("remark");

													ballTeamVo.arank = keyJSON.getString("arank");
													ballTeamVo.ateam = keyJSON.getString("ateam");
													ballTeamVo.hscore = keyJSON.getString("hscore");
													ballTeamVo.round = keyJSON.getString("round");

													arrayList.add(ballTeamVo);
												}

											}

											footballdayVo.setTime(key);
											footballdayVo.setBallarrayList(arrayList);
											maplist.add(footballdayVo);
										}
										myHandler.sendEmptyMessage(1);

									}

								}

								Log.e("-----", maplist.toString());

							} else {

								MyToast.getToast(activity, item.optString("msg")).show();
							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Log.i("RealTime", "request--------success------" + error);

						MyToast.getToast(activity, "获取失败").show();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {

				Map<String, String> params = new HashMap<String, String>();
				// params.put("appid", "0af5281058488ec1784e433f69d45d81");
				// params.put("custNo", "gl00014156");
				// params.put("orderId", attach);

				return params;
			}
		};

		jsonObjectRequest.setShouldCache(false);// 是否设置缓存

		mySingleton.addToRequestQueue(jsonObjectRequest);

	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				if (NetWork.isConnect(activity)) {
					getSaomaXplay();
					// loadInfoview();

				} else {
					MyToast.getToast(activity, "网络连接异常，请检查网络").show();

				}
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1500);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		App.footballBfPosition=reshId;
		myHandler.removeMessages(3);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getSaomaXplay();

	}

	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			ProgressDialogBar.stopProgress();
			switch (msg.what) {
			case 0:

				break;
			case 1:
				if (maplist != null) {
					
					adapter.setMaplist(maplist);
					expandableListView.setAdapter(adapter);
					
					adapter.fresh();
					
					if (isFresh) {
						expandableListView.setSelection(App.footballBfPosition);
						isFresh=false;
						Log.e("------", App.footballBfPosition+"");
					}else {
						expandableListView.setSelection(getRealId);
					}
					
				
					expandableListView.setGroupIndicator(null);
					// 遍历所有group,将所有项设置成默认展开
					
						int groupCount = expandableListView.getCount();
						for (int i = 0; i < groupCount; i++) {
							expandableListView.expandGroup(i);
						}
						
					
					myHandler.sendEmptyMessageDelayed(3, 60000);
				}

				break;
			case -2:

				break;
			case -1:

				break;
			case 3:
				myHandler.removeMessages(3);
				
				getSaomaXplay();
				break;
			case 4:

				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}
}
